package com.situ.stmall.admin.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.stmall.admin.entity.Root;
import com.situ.stmall.admin.mapper.RootMapper;
import com.situ.stmall.admin.service.RootService;
import com.situ.stmall.admin.util.MD5Util;


@Service
public class RootServiceImpl implements RootService {

	@Autowired
	private RootMapper rootMapper;
	@Override
	public Root login(Root root) throws Exception {
		//账号判断，长度 
		if (root.getRootname() == null || 
			root.getRootname().length() < 3 || 
			root.getRootname().length() > 16) {
			throw new Exception("账号格式错误");
			
		}
		//密码判断，长度，校验
		if (root.getPassword() == null || 
			root.getPassword().length() < 3 || 
			root.getPassword().length() > 16) {
			throw new Exception("密码格式错误");
		}
		
		//判断账号是否存在
		Root selectRoot = rootMapper.selectByRootName(root.getRootname());
		if (selectRoot == null) {
			throw new Exception("账号不存在");
		}
		
		//密码校验
		if ( ! selectRoot.getPassword().equals(MD5Util.getMD5(root.getPassword()))) {
			throw new Exception("密码错误");
		}
		if (selectRoot.getStatus() != 0) {
			throw new Exception("账号被禁用");
		}
		
		return selectRoot;
	}
	@Override
	public Root editRoot(Root root,String repassword) throws Exception {
		// 密码判断，
		if ( ! root.getPassword().equals(repassword)) {
			
			throw new Exception("密码不一致");
		}
		//password格式判断
		if (root.getPassword() ==null || 
			root.getPassword().length() < 3 || 
			root.getPassword().length() > 16) {
			throw new Exception("密码格式不正确");
		}
		
		
		int result =rootMapper.updateByPrimaryKey(root);
		
		
		return rootMapper.selectByPrimaryKey(root.getId());
		
		
	}
	@Override
	public Root reg(Root root,String repassword) throws Exception {
		
		//账号判断，长度 
		if (root.getRootname() == null || 
			root.getRootname().length() < 3 || 
			root.getRootname().length() > 16) {
			throw new Exception("账号格式错误");
			
		}
		//密码判断，长度，校验
		if (root.getPassword() == null || 
			root.getPassword().length() < 3 || 
			root.getPassword().length() > 16) {
			throw new Exception("密码格式错误");
		}
		//重复密码校验
		if (!root.getPassword().equals(repassword)) {
			throw new Exception("密码不一致");
		}
		rootMapper.insert(root);
		
		return rootMapper.selectByPrimaryKey(root.getId());
	}
	@Override
	public Root getByRootName(String rootname) {
		// TODO Auto-generated method stub
		return rootMapper.selectByRootName(rootname);
	}

}
